package com.kd.d5000acquire.util;

import lombok.extern.slf4j.Slf4j;
import org.dom4j.*;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.*;
import java.util.*;

@Slf4j
public class XmlUtil {

    public static Map<String, String> transformXml(String xml) {
        Map<String, String> map = new HashMap<String, String>();
        Document doc = null;
        try {
            doc = DocumentHelper.parseText(xml);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        Element rootElt = doc.getRootElement();
        rootElt = rootElt.element("data");
        // 解析子节点的信息
        Iterator list = rootElt.elementIterator();
        //Map<String,Object> map=new HashMap<>();
        while (list.hasNext()) {
            Element listChild = (Element) list.next();
            String cName = listChild.getName();
            String cValue = listChild.getStringValue();
            map.put(cName, cValue);
        }
        return map;
    }

    /**
     * 解析告警的xml
     *
     * @param xml
     * @return
     */
    @SuppressWarnings({"unchecked", "rawtypes", "unused"})
    public static Map<String, String > alarmXml(String xml) {
        Map<String, String> map = new HashMap<String, String>();
        try {
            //将xml字符串转换成xml
            Document doc = DocumentHelper.parseText(xml);
            Element rootElt = doc.getRootElement();
            //当前节点的名称、文本内容和属性
            List<Attribute> listAttr = rootElt.attributes();//当前节点的所有属性的list
            for (Attribute attr : listAttr) {//遍历当前节点的所有属性
                String name = attr.getName();//属性名称
                String value = attr.getValue();//属性的值
                map.put(rootElt.getName(), value);
            }

            //递归遍历当前节点所有的子节点
            // 解析子节点的信息
            Iterator list = rootElt.elementIterator();
            //Map<String,Object> map=new HashMap<>();
            while (list.hasNext()) {
                Element listChild = (Element) list.next();
                String cName = listChild.getName();
                String cValue = listChild.getStringValue();
                map.put(cName, cValue);
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        } /// 将字符串转为XML

        return map;
    }


    /**
     * XML 字符串生成xml文件
     * @param str
     * @param filePath
     * @param fileName
     * @throws IOException
     * @throws DocumentException
     */
    public static void strChangeXML(String str,String filePath,String fileName) throws IOException, DocumentException {
        SAXReader saxReader = new SAXReader();
        //  String path = System.getenv("MONITOR_HOME");
        String path = System.getenv("MONITOR_HOME");
        String nameAndPath = path+"/"+filePath+"/"+fileName;
        Document document;
        //saxReader.setEncoding("GB2312");
        document = saxReader.read(new ByteArrayInputStream(str.getBytes("UTF-8")));
        //document = saxReader.read(new ByteArrayInputStream(str.getBytes()));
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("GB2312");
        // format.setSuppressDeclaration(true);
        /** 将document中的内容写入文件中 */

        File file =new File(nameAndPath);
        //目录不存在新建目录
        if(!file.getParentFile().exists()){
            file.getParentFile().mkdirs();
        }
        if(file.exists()){
            file.delete();
        }
        file.createNewFile();
        // XMLWriter writer = new XMLWriter(new FileWriter(file),format);
        XMLWriter writer = new XMLWriter(new OutputStreamWriter(new FileOutputStream(file),"GB2312"),format);
        //BufferedWriter bf=new BufferedWriter(writer);
        //  writer.writeDeclaration
        // StandaloneWriter writer = new StandaloneWriter(new FileOutputStream(filePath),format);
        writer.write(document);
        try {
            writer.close();
        }catch (Exception e){

        }finally {
            if (writer!=null){
                writer=null;
            }
        }
    }


    public static String generateAppStatusXml(Map<String, String> map) {
        String str = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                "<type id=\"10031d\">\n" +
                "<action>notice</action>\n" +
                "<device_id>-</device_id>\n" +
                "<nodename>${TABLE_NAME}</nodename>\n" +
                "<time>${OCCUR_TIME}</time>\n" +
                "<definition_id>${DEFINITION_ID}</definition_id>\n" +
                "<data>${CONTENT}</data>\n" +
                "</type>\n";
        str = str.replace("${TABLE_NAME}", map.get("TABLE_NAME"));
        str = str.replace("${OCCUR_TIME}", map.get("OCCUR_TIME"));
        str = str.replace("${CONTENT}", map.get("CONTENT"));
        str = str.replace("${DEFINITION_ID}",map.get("DEFINITION_ID"));
        log.info("告警xml已生成：\n"+str);
        return str;
    }

    public static String generateAppStatusRecoverAlarmXml(Map<String, String> map) {
        String str = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                "<type id=\"10031d\">\n" +
                "<action>recover</action>\n" +
                "<device_id>-</device_id>\n" +
                "<nodename>${TABLE_NAME}</nodename>\n" +
                "<time>${RECOVER_TIME}</time>\n" +
                "<definition_id>${DEFINITION_ID}</definition_id>\n" +
                "<data>${CONTENT}</data>\n" +
                "</type>\n";
        str = str.replace("${TABLE_NAME}", map.get("TABLE_NAME"));
        str = str.replace("${RECOVER_TIME}", map.get("RECOVER_TIME"));
        str = str.replace("${CONTENT}", map.get("CONTENT"));
        str = str.replace("${DEFINITION_ID}",map.get("DEFINITION_ID"));
        log.info("恢复告警xml已生成：\n"+str);
        return str;
    }
}
